#include <iostream>
#include <string.h>

#include <stdlib.h>
#include <stdio.h>

#include <sys/time.h>
#include <unistd.h>
#include <sys/select.h>

#include "backup.h"

CBackup::CBackup(int sizebuffer, int nimgs, CvSize size1, ...)
{
    int i, j;
    m_sizebuffer = sizebuffer;
    buffer_to_show = buffer_to_store = 0;

    va_list size_list;
    CvSize size0;
    va_start (size_list, size1);
    size0 = size1;
    j=0;
    while (j<nimgs)//size0.width)
    {
	imgsbuffer.set_capacity(j+1);
	sizesbuffer.set_capacity(j+1);
	sizesbuffer.push_back(size0);
	imgsbuffer.push_back(ImageBuffer_t (m_sizebuffer));
	for (i=0; i<m_sizebuffer; i++)
	    imgsbuffer[j].push_back(cvCreateImage(sizesbuffer[j],IPL_DEPTH_8U,3));
	size0 = va_arg(size_list, CvSize);
	j++;
    }
    va_end(size_list);
    m_nbuffers = j;
}

void CBackup::alloc(int nimgs, CvSize size1, ...)
{
    int i, j;
    buffer_to_show = buffer_to_store = 0;

    va_list size_list;
    CvSize size0;
    va_start (size_list, size1);
    size0 = size1;
    j=0;
    while (j<nimgs)//size0.width)
    {
	imgsbuffer.set_capacity(j+1);
	sizesbuffer.set_capacity(j+1);
	sizesbuffer.push_back(size0);
	imgsbuffer.push_back(ImageBuffer_t (m_sizebuffer));
	for (i=0; i<m_sizebuffer; i++)
	    imgsbuffer[j].push_back(cvCreateImage(sizesbuffer[j],IPL_DEPTH_8U,3));
	size0 = va_arg(size_list, CvSize);
	j++;
    }
    va_end(size_list);
    m_nbuffers = j;
}

IplImage * CBackup::img(unsigned int n) {
    return imgsbuffer[n][buffer_to_show];
}

IplImage * CBackup::operator [] (unsigned int n) {
    return imgsbuffer[n][0];//buffer_to_show];
}

void CBackup::copy_backup(IplImage **img1, ...)
{
    int j;
    va_list list;
    IplImage **img0 = img1;
    IplImage *image;
    buffer_to_show = 0;
    va_start (list, img1);

    for (j=0; j<m_nbuffers; j++)
    {
	image = imgsbuffer[j].back();
	imgsbuffer[j].pop_back();
	*img0 = image;
	imgsbuffer[j].push_front(image);
	img0 = va_arg(list, IplImage**);
    }
    va_end(list);	
}

void CBackup::copy_backup()
{
    int j;
    IplImage *image;
    buffer_to_show = 0;

    for (j=0; j<m_nbuffers; j++)
    {
	image = imgsbuffer[j].back();
	imgsbuffer[j].pop_back();
	imgsbuffer[j].push_front(image);
    }
}

void CBackup::rewind() {
    buffer_to_show =0;
}

int CBackup::back_one()
{
    buffer_to_show++;
    buffer_to_show = (buffer_to_show + m_sizebuffer)% m_sizebuffer;
    return  buffer_to_show;
}
int CBackup::forward_one()
{
    buffer_to_show--;
    buffer_to_show = (buffer_to_show + m_sizebuffer)% m_sizebuffer;
    return  buffer_to_show;
}
